package com.myproject.utils;

import java.lang.reflect.Field;
import java.util.*;

public class BeanCopy {

    public static final List<String> baseTypes = Arrays.asList("byte","short","int","long","float","double","boolean","char");
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Boy boy = new Boy();
        boy.setAge(10);
        Class c = boy.getClass();
        System.out.println(c);
        Field[] fields = c.getDeclaredFields();
        for (Field field:fields){
            System.out.println(field.toGenericString());
            System.out.println(field.toString());
            System.out.println(field.getName());
            System.out.println(field.getType());
        }

        Field field = c.getDeclaredField("age");
        field.setAccessible(true);
        System.out.println(field.toString());
        System.out.println(field.get(boy));
        System.out.println(field.get(boy).getClass());

    }

    /*
    * 深拷贝
    * */
    public static Object copy(Object obj){

        try {
            if (obj instanceof String){
                return new String((String) obj);
            } else if (obj instanceof Number){
                return obj;
            } else if (obj instanceof Map){
                Map from = (Map) obj;
                Map to = (Map) obj.getClass().newInstance();
                to.putAll(from);
                return to;
            } else if (obj instanceof Set){
                Set from = (Set) obj;
                Set to = (Set) obj.getClass().newInstance();
                to.addAll(from);
                return to;
            } else if (obj instanceof List){
                List from = (List) obj;
                List to = (List) obj.getClass().newInstance();
                to.addAll(from);
                return to;
            } else {
                Object toObj = obj.getClass().newInstance();
                Field[] fields = obj.getClass().getDeclaredFields();
                for (Field field:fields){
                    field.setAccessible(true);
                    Object var = field.get(obj);
                    if (var!=null){
                        Object var2 = copy(var);
                        String fieldName = field.getName();
                        Field toField = toObj.getClass().getDeclaredField(fieldName);
                        toField.setAccessible(true);
                        toField.set(toObj,var2);
                    }
                }
                return toObj;
            }

        } catch (Exception e){
            throw new RuntimeException(e);
        }

    }
}
